<template>
  <div class="userContainer">
    <div class="search">
      <el-input v-model.trim="searchValue" placeholder="请输入用户名或用户电话" clearable :prefix-icon="Search" @keyup="getUserList(searchValue)">
        <template #append>
          <el-button :icon="Search" @click="getUserList(searchValue)"/>
        </template>
      </el-input>
      <el-button style="margin-left: 30px;" type="primary" @click="addUserVisible = true">新建用户</el-button>
      <el-button style="margin-left: 30px;" type="primary" @click="fileInPut = true">批量导入</el-button>
      <el-button type="success" @click="fileOutPut = true">导出</el-button>

      <el-dialog v-model="addUserVisible" title="添加用户" width="30%" draggable>
        <el-form v-model="addUserForm">
          <el-form-item prop="用户名称">
            <el-input v-model="addUserForm.userName" placeholder="请输入用户名" :prefix-icon="User"/>
          </el-form-item>
          <el-form-item prop="初始密码">
            <el-input v-model="addUserForm.password" placeholder="请输入用户初始密码" :prefix-icon="Lock"/>
          </el-form-item>
          <el-form-item prop="联系电话">
            <el-input v-model="addUserForm.tel" placeholder="请输入用户电话" :prefix-icon="Iphone"/>
          </el-form-item>
          <el-form-item prop="学院信息">
            <el-cascader v-model="addUserForm.collegeMessage" :options="collegeOptions" @change="handleChange" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addUserVisible = false">取消</el-button>
            <el-button type="primary" @click="addUser()">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 导出表格弹框 -->
     <el-dialog v-model="fileOutPut" title="表格导出" width="30%" @close="close">
            <el-input v-model="name" placeholder="请输入导出文件的文件名"></el-input>
            <el-alert title="默认文件名为（导出测试）" type="info" :closable="false" style="margin-top: 10px;" />
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="fileOutPut = false">取消</el-button>
                    <el-button type="primary" @click="save">确定</el-button>
                </span>
            </template>
      </el-dialog>
    <el-table :data="tableData" stripe style="width: 100%;margin-top: 10px;" height="50%" id="el-table">
    <el-table-column prop="userId" label="用户ID" width="85"/>
    <el-table-column prop="userName" label="用户名字" width="85"/>
    <el-table-column prop="tel" label="电话" />
    <el-table-column prop="roleName" label="角色" :filters="[
        { text: '检察员', value: '检察员' },
        { text: '学生', value: '学生' },]" :filter-method="filterName"  filter-placement="bottom-end">
    </el-table-column>
    <el-table-column prop="userCode" label="用户学号" />
    <el-table-column label="紧急联系人">
      <el-table-column prop="contactName" label="姓名" />
      <el-table-column prop="contactPhone" label="电话" />
      <el-table-column prop="contactRelation" label="与联系人关系" />
    </el-table-column> 
    <el-table-column prop="univerName" label="所在学校" />
    <el-table-column prop="collegeName" label="所在学院" width="150" />
    <el-table-column fixed="right" label="操作" width="125">
      <template #default="row">
        <el-tooltip content="详情" placement="bottom">
          <el-button link type="primary" :icon="Postcard"  class="myLink" @click="getDetailMessage(row)"></el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="bottom">
          <el-button link type="danger" :icon="Delete"  class="myLink" @click="deleteUser(row)"></el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="detailMessage" title="详情" width="30%" draggable>
    <el-form v-model="detailUser" label-position="left">
      <el-form-item prop="userId" label="用&nbsp;&nbsp;&nbsp;户&nbsp;&nbsp;&nbsp;ID: " size="5px">
        <span>{{detailUser.userId}} </span>
      </el-form-item>
      <el-form-item prop="userName" label="名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;字: ">
        <span>{{detailUser.userName}} </span>
      </el-form-item>
      <el-form-item prop="userCode"  width="100" label="用&nbsp;户&nbsp;学&nbsp;号: ">
        <span>{{detailUser.userCode}} </span>
      </el-form-item>
      <el-form-item prop="password"  width="100" label="密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码: ">
        <span>{{detailUser.password}} </span>
      </el-form-item>
      <el-form-item prop="detail"  width="100" label="学&nbsp;院&nbsp;详&nbsp;细: ">
        <span>{{detailUser.detail}} </span>
      </el-form-item>
      <el-form-item prop="cdId"  width="100" label="学&nbsp;院&nbsp;详&nbsp;细&nbsp;ID: ">
        <span>{{detailUser.cdId}} </span>
      </el-form-item>
      <el-form-item prop="collegeId"  width="100" label="学&nbsp;&nbsp;院&nbsp;&nbsp;&nbsp;ID: ">
        <span>{{detailUser.collegeId}} </span>
      </el-form-item>
      <el-form-item prop="collegeName"  width="100" label="学&nbsp;院&nbsp;名&nbsp;称: ">
        <span>{{detailUser.collegeName}} </span>
      </el-form-item>
      <el-form-item prop="tel"  width="100" label="联&nbsp;系&nbsp;电&nbsp;话: ">
        <span>{{detailUser.tel}} </span>
      </el-form-item>
      <el-form-item prop="univerName"  width="100" label="学&nbsp;校&nbsp;名&nbsp;称: ">
        <span>{{detailUser.univerName}} </span>
      </el-form-item>
      <el-form-item prop="contactName"  width="100" label="联&nbsp;系&nbsp;人&nbsp;姓&nbsp;名: ">
        <span>{{detailUser.contactName}} </span>
      </el-form-item>
      <el-form-item prop="contactPhone"  width="100" label="联&nbsp;系&nbsp;人&nbsp;电&nbsp;话: ">
        <span>{{detailUser.contactPhone}} </span>
      </el-form-item>
      <el-form-item prop="contactRelation"  width="100" label="联&nbsp;系&nbsp;人&nbsp;关&nbsp;系: ">
        <span>{{detailUser.contactRelation}} </span>
      </el-form-item>
      <el-form-item prop="picture"  width="100" label="头&nbsp;像&nbsp;图&nbsp;片: ">
        <img :src="detailUser.picture" style="width: 50px;height: 50px;" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailMessage = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <div class="pagination">
    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>
  </div>
</template>

<script setup>
import { reactive , inject , onMounted , ref ,nextTick} from "vue"
import axios from '../../axios/axiosInstance'
import { ElLoading ,ElMessage,ElMessageBox} from 'element-plus'
import { Delete ,Search ,User,Lock,Iphone,Postcard,UploadFilled} from '@element-plus/icons-vue'
import FileSaver from "file-saver";
import * as XLSX from 'xlsx';
// import FileIn from "../../components/file/Excel.vue"

//变量定义
const addUserVisible = ref(false)
let name = "";
const fileOutPut = ref(false)
const fileInPut = ref(false)
const collegeOptions = reactive()
let tableData = reactive([])
let addUserForm = reactive({
  userName: "",
  tel: "",
  password: "",
  collegeMessage: "",
})
let detailMessage = ref(false)
const total = ref(0)
let searchValue = ref()
let page = 1
let size = 5
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const detailUser = reactive({
  cdId: 1,
  collegeId: 1,
  collegeName: "计算机科学与技术学院", 
  contactId: 30001,
  contactName: "张素珍",
  contactPhone: 13788987787,
  contactRelation: "父亲",
  detail: "计科194班",    
  password: "111111",
  picture: "https://i.328888.xyz/2023/05/10/iYkUdL.jpeg",
  tel: "16684867746",
  token: "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MjAwMDEsIm1vYmlsZSI6IjE2Njg0ODY3NzQ2Iiwic3ViIjoidXVzaG9wLXVzZXIiLCJleHAiOjE2ODM3OTY0MzUsImp0aSI6ImI4MTcxZDExLTQyODItNDYyOC1hYWU5LWQ1MzA3Yjk2YzUxMiJ9.WTBZHeyB4We40u7qh_DXIk_YdgvPj2wZ6D-YWVh_gss",
  univerId: 1,
  univerName: "贵州大学",
  userCode: "1821000263",
  userId: 20001,
  userName: "乔治"
})

//方法 

const getDetailMessage = (row) => {
  detailMessage.value = true;
  detailUser.userId = row.row.userId,
  detailUser.userName = row.row.userName,
  detailUser.userCode = row.row.userCode,
  detailUser.cdId = row.row.cdId,
  detailUser.collegeId = row.row.collegeId,
  detailUser.collegeName = row.row.collegeName,
  detailUser.contactId = row.row.contactId,
  detailUser.contactName = row.row.contactName,
  detailUser.contactPhone = row.row.contactPhone,
  detailUser.contactRelation = row.row.contactRelation,
  detailUser.detail = row.row.detail,
  detailUser.picture = row.row.picture,
  detailUser.password = row.row.password,
  detailUser.tel = row.row.tel,
  detailUser.univerName = row.row.univerName
}

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  size = val
  init()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  page = val
  init()
}
const filterName = (value, row) => {
  return row.roleName === value
}


 const clear = (value) => {
    Object.keys(value).map(key => {
      delete value[key]
    })
  }

  const handleChange = (value) => {
    console.log()
  console.log(value)
}

const save = () => {
   nextTick(function () {
        let filename = ''
        const xlsxParam = { raw: true } //转化成Excel使用原始格式
        const elTable = XLSX.utils.table_to_book(document.getElementById('el-table'), xlsxParam)
        if (name === '') {
        	// 默认导出文件名
            filename = '导出测试.xlsx'
        } else {
            filename = name += '.xlsx'
        }
        const wbout = XLSX.write(elTable, { bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
            FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)
        } catch (e) {
            if (typeof console !== 'undefined') {
                console.log(e, wbout)
            }
        }
        return wbout
    })
}

const addUser = () => {
   //将数据发往后端
   console.log(addUserForm)
  axios.post('/account-service/user/oneUser/',addUserForm).then((res) => {   
        console.log("res是：")
        console.log(res)
        console.log("res.data是：")
        console.log(res.data)
        console.log("res.data.data是：")
        console.log(res.data)
        if(res.code == 200){
          //添加管理员成功成功
          ElMessage({type: "success",message: "添加成功"});
          tableData.push(res.data)
        }else{
          //登录失败
         ElMessage({type: "error",message: res.msg})
         addAdminVisable = false;
        }
    }).catch((err) => {
      console.log(err)

    })
}


const getInitOptions = () => {
   axios.get('/contact-service/college/collegeOption').then((res) => {   
        console.log("res是：")
        console.log(res)
        console.log("res.data是：")
        console.log(res.data)
        console.log("optionsoptions是：")
        console.log(res.data)
        if(res.code == 200){
          collegeOptions = res.data
          console.log("得到的值为：")
          console.log(collegeOptions)
        }else{
        }
    }).catch((err) => {
      console.log(err)

    })
}
const deleteUser = (row) => {
  console.log(row);
  console.log(row.row);
  console.log(row.$index)
  console.log(row.row.userId);
  let name = row.row.userName
  ElMessageBox.confirm(
    '确定要删除用【'+name+'】吗？',
    '温馨提示',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      let userId = row.row.userId;
      console.log(userId)
      axios.delete('/account-service/user/deleteOne/'+userId).then((res) => {
        console.log(res)
        if(res.code == 200){
          ElMessage({type: "success",message: "删除成功"});
          tableData.pop(row.$index)
        }else{
          ElMessage({type: "error",message: "删除失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    }) 

}

//根据关键字模糊查询用户
const getUserList = (searchValue) => {
  if(searchValue != ''){
    axios.get(`/account-service/user/userList/${searchValue}`).then((res) => {
        console.log(res)
        
        if(res.code == 200){
          clear(tableData)
          for(let i in res.data){
            console.log(i)
            tableData.push(res.data[i])
          }
          ElMessage({type: "success",message: "查询成功"});
        }else{
          ElMessage({type: "error",message: "查询失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
  }else{
    init()
  }
}

const init = () => {
  const loading = ElLoading.service({
        lock: true,
        text: '拼命加载中',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        loading.close()
      }, 2000)
     axios.get(`/account-service/user/userList/${page}/${size}`).then((res) => {   
      console.log(res)
      clear(tableData)
      // total.value = res.data.total
      console.log(total)
      for(let i in res.data.content){
        console.log(i)
        tableData.push(res.data.content[i])
      }
      console.log("最后的tableData是：")
      console.log(tableData)
    }).catch((err) => {

      console.log(err)

    })
}

//页面初始化方法
onMounted(()=>{ 
  init()
  getInitOptions()
})
</script>

<style scoped>
.userContainer .search{
  display: flex;
  width: 600px;
}
.userContainer .pagination{
  justify-content: center;
 margin-top: 15px;
}

</style>
